//
//  MonthBillView.m
//  TengyunStation
//
//  Created by Johnny on 15/8/27.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "MonthBillView.h"
#import "DayExpress.h"
#import "TSHeader.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "MonthBillCell.h"

#define DaySocketTag    10

@interface MonthBillView ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
}

@end
@implementation MonthBillView

- (id)initWithFrame:(CGRect)frame SearchTime:(NSString *)searchTime SearchType:(NSString *)searchType {
    self = [super initWithFrame:frame];
    if (self) {
        self.dataSource = self;
        self.delegate = self;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.backgroundColor = UIColorFromRGB(0xf1f1f1);
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 38)];
        footerView.backgroundColor = [UIColor clearColor];
        self.tableFooterView = footerView;
        self.searchTime = searchTime;
        self.searchType = searchType;
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        [self getThisMonExpressListSocket];
    }
    return self;
}

- (void)showBottomViewWithTab:(NSInteger)tab {
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(self.frame.origin.x, (self.frame.size.height - 38), 320, 38)];
    bottomView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    UILabel *countLabel = [[UILabel alloc] initWithFrame:CGRectMake(145, 9, 150, 20)];
    countLabel.backgroundColor = [UIColor clearColor];
    countLabel.textColor = [UIColor whiteColor];
    countLabel.font = [UIFont systemFontOfSize:15];
    countLabel.textAlignment = NSTextAlignmentRight;
    countLabel.attributedText = [self countLabelAttributedString];
    [bottomView addSubview:countLabel];
    [self.superview insertSubview:bottomView aboveSubview:self];
}

//刷新底部快递总量数据
- (NSAttributedString *)countLabelAttributedString {
    int expressCount = 0;
    for (DayExpress *dayExpress in self.dayExpressList) {
        expressCount += dayExpress.expressCount;
    }
    NSString *countString = [NSString stringWithFormat:@"%d",expressCount];
    NSString *string = [NSString stringWithFormat:@"共计:%@件",countString];
    NSRange range = [string rangeOfString:countString];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
    [attString addAttribute:NSForegroundColorAttributeName value:OrangeColor range:range];
    return attString;
}


- (void)getThisMonExpressListSocket {
    if (self.dayExpressList.count <= 0) {
        [self makeLoading];
    } else {
        [self makeNone];
    }
    DLog(@"%@,,,%@",self.searchType,self.searchTime);
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR1"]];
    [mutableData appendBytes:[SocketMethod checkLegal:self.searchType] length:2];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.searchTime] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//每天快件查询
- (void)getZitiExpressListSocketWithDay:(NSString *)day Tag:(NSInteger)tag {
    [ToastActivity makeActivity:@"加载中..." InView:self];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR2"]];
    [mutableData appendBytes:[SocketMethod checkLegal:self.searchType] length:2];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:day] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:(DaySocketTag + tag)];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dayExpressList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    DayExpress *dayExpress = [self.dayExpressList objectAtIndex:section];
    if (dayExpress.isOpen) {
        return dayExpress.expressList.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    DayExpress *dayExpress = [self.dayExpressList objectAtIndex:section];
    NSString *title = [NSString stringWithFormat:@"%@(%d)",dayExpress.showDay,dayExpress.expressCount];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor whiteColor];
    button.frame = CGRectMake(0, 0, 320, 44);
    button.tag = section;
    [button addTarget:self action:@selector(openTableSection:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, 150, 20)];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = MainTextColor;
    titleLabel.text = title;
    [button addSubview:titleLabel];
    button.layer.borderColor = LineColor.CGColor;
    button.layer.borderWidth = 0.5;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(290, 11, 22, 22)];
    if (dayExpress.isOpen) {
        imageView.image = [UIImage imageNamed:@"beny_icon_zhan_pre"];
    } else {
        imageView.image = [UIImage imageNamed:@"beny_icon_zhan"];
    }
    [button addSubview:imageView];
    return button;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"MonthBillCell";
    MonthBillCell *cell = [self dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MonthBillCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    DayExpress *dayExpress = [self.dayExpressList objectAtIndex:indexPath.section];
    DayEveryExpress *dayEveryExpress = [dayExpress.expressList objectAtIndex:indexPath.row];
    [cell reloadMonthBillCell:dayEveryExpress];
    return cell;
}

#pragma mark action
- (void)openTableSection:(UIButton *)button {
    DayExpress *dayExpress = [self.dayExpressList objectAtIndex:button.tag];
    if (dayExpress.expressList.count > 0) {
        dayExpress.isOpen = !dayExpress.isOpen;
        [self reloadMonthBillViewSection:button.tag];
    } else {
        [self getZitiExpressListSocketWithDay:dayExpress.expressday Tag:button.tag];
    }
}

- (void)reloadMonthBillViewSection:(NSInteger)section {
    [self reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            NSArray *array = [content componentsSeparatedByString:@"|"];
            NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
            int expressCount = 0;
            for (NSString *string in array) {
                if (string.length > 0) {
                    DayExpress *dayExpress = [[DayExpress alloc] initWithString:string];
                    expressCount += dayExpress.expressCount;
                    [mutableArray addObject:dayExpress];
                }
            }
            self.dayExpressList = mutableArray;
            if (self.dayExpressList.count > 0) {
                [self makeNone];
                [self showBottomViewWithTab:expressCount];
                [self reloadData];
            } else {
                if ([self.searchType isEqualToString:@"01"]) {
                    [self makeTip:@"无自提件"];
                } else {
                    [self makeTip:@"无上门件"];
                }
            }
        } else {
            [self makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getThisMonExpressListSocket)];
        }
    } else if (socket.socketTag >= DaySocketTag) {
        if ([code isEqualToString:SuccessSocket]) {
            [ToastActivity dismissInView:self];
            int number = socket.socketTag - DaySocketTag;
            DayExpress *dayExpress = [self.dayExpressList objectAtIndex:number];
            NSString *content = [SocketMethod stringDecryHexData:data];
            [dayExpress setExpressListString:content];
            [self reloadMonthBillViewSection:number];
        } else {
            [ToastActivity makeError:msg InView:self];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    if (socket.socketTag == 1) {
        [self makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getThisMonExpressListSocket)];
        [DSToast showText:msg InView:self.superview];
    } else {
        [ToastActivity makeError:msg InView:self];
    }
}

- (void)dealloc {
    _socketRequest = nil;
    _dayExpressList = nil;
}

@end
